import { type FormPanelObject, Utils } from 'lfun-bg-comp';
import { getCity, getCountry, getProvince, getProvinceCity } from '@/service';
import { sessionSearch } from '@/service/student/session';
import { listClasses } from '@/service/unit/classes';
import { listGradeType, listGrades } from '@/service/unit/grades';
import { allMajor, searchMajor } from '@/service/unit/major';
import {
  SearchSchool,
  SearchSchoolByNameParams,
  getSchool,
  searchByNameSchool,
  searchSchool,
  searchSchoolByName,
} from '@/service/unit/school';
import { getPlanningSchoolById, searchPlanningSchoolByName } from './unit/planning';
import { searchOrg } from './unit/org';
import { SCHOOL_OPERATION_TYPE } from '@/constant/schoolOptions';
import { TeachersSrv } from './teacher';
import { getStuInfo } from './student/instudent';
import { selectedCourse } from './unit/course';

export const getProvinceCityCascader = async (
  form: FormPanelObject,
  selectedOptions: Array<any>,
  filters: Array<string> = []
): Promise<any> => {
  if (!selectedOptions || selectedOptions.length === 0) {
    const r: any = await getProvince();
    const list: Array<any> = [];
    if (r.success) {
      r.data.items.forEach(item => {
        if (!filters.includes(item.enum_value)) {
          list.push({
            label: item.description,
            value: item.enum_value,
            isLeaf: false,
          });
        }
      });
      return list;
    }
  }
  if (selectedOptions.length === 1) {
    const r = await getCity(selectedOptions[0].value);
    if (r.success) {
      return r.data?.items?.map(item => {
        return {
          label: item.description,
          value: item.enum_value,
          isLeaf: false,
        };
      });
    }
  }
  if (selectedOptions.length === 2) {
    const r = await getCountry(selectedOptions[1].value);
    if (r.success) {
      return r.data?.items?.map(item => {
        return {
          label: item.description,
          value: item.enum_value,
        };
      });
    }
  }
  return [];
};

export const getProvinceCityOptions = async (filters?: string[]): Promise<any> => {
  const r: any = await getProvinceCity();
  let list = [];
  if (r.success) {
    const provincies = r.data?.items.filter(
      item => item.enum_name === 'province' && !filters?.includes(item.enum_value)
    );
    const cities = r.data?.items.filter(item => item.enum_name === 'city' && !filters?.includes(item.enum_value));
    list = provincies.map(item => {
      return {
        label: item.description,
        value: item.enum_value,
        children: cities
          .filter(city => city.parent_id === item.enum_value)
          .map(item => {
            return {
              label: item.description,
              value: item.enum_value,
            };
          }),
      };
    });
  }
  return list;
};

export const getProvinceOptions = async (): Promise<any> => {
  const r: any = await getProvinceCity();
  let list = [];
  if (r.success) {
    const provincies = r.data?.items.filter(item => item.enum_name === 'province');
    list = provincies.map(item => {
      return {
        label: item.description,
        value: item.enum_value,
      };
    });
  }
  return list;
};

export const getCityOptions = async (form: FormPanelObject, fieldKey?: string): Promise<any> => {
  let list = [];
  fieldKey = fieldKey || 'province';
  if (form && (form.getFieldsValue() || {})[fieldKey]) {
    const r: any = await getCity(form.getFieldsValue()[fieldKey]);

    if (r.success) {
      const cities = r.data?.items;
      list = cities.map(item => {
        return {
          label: item.description,
          value: item.enum_value,
        };
      });
    }
    return list;
  }
  return list;
};

export const getCountryOptions = async (formPanelObject: FormPanelObject, fieldKey?: string): Promise<any> => {
  fieldKey = fieldKey || 'province';
  if (formPanelObject && (formPanelObject.getFieldsValue() || {})[fieldKey]) {
    const r = await getCountry(formPanelObject.getFieldsValue()[fieldKey][1]);
    if (r.success) {
      return r.data?.items?.map(item => {
        return {
          label: item.description,
          value: item.enum_value,
        };
      });
    }
  }
  return [];
};

export const getCountryOptionsByCity = async (formPanelObject: FormPanelObject, fieldKey?: string): Promise<any> => {
  fieldKey = fieldKey || 'city';
  if (formPanelObject && (formPanelObject.getFieldsValue() || {})[fieldKey]) {
    const r = await getCountry((formPanelObject.getFieldsValue() || {})[fieldKey]);
    if (r.success) {
      return r.data?.items?.map(item => {
        return {
          label: item.description,
          value: item.enum_value,
        };
      });
    }
  }
  return [];
};

export const getMajorOptions = async (): Promise<any> => {
  const mjres = await allMajor();
  let list = [];
  if (mjres.success) {
    const mj1 = mjres.data.items.filter(item => item.enum_name === 'major');
    const mj2 = mjres.data.items.filter(item => item.enum_name === 'major_lv2');
    list = mj1.map(item => {
      return {
        label: item.description,
        value: item.enum_value,
        key: item.enum_value,
        children: mj2
          .filter(subitem => subitem.parent_id === item.enum_value)
          .map(subitem => {
            return {
              label: subitem.description,
              value: String(subitem.enum_value),
              key: subitem.enum_value,
            };
          }),
      };
    });
  }
  return list;
};

export const getSessionOptions = async (): Promise<any> => {
  const ssR = await sessionSearch({});
  let list = [];
  if (ssR.success) {
    list = ssR.data?.items?.map(item => ({
      label: item.session_name,
      value: String(item.session_id),
      key: item.session_id,
    }));
  }
  return list;
};

export const getSchoolOptions = async (form: FormPanelObject): Promise<any> => {
  if (form && form.getFieldsValue()?.area_id) {
    const area_id = form.getFieldsValue().area_id;
    const params: SearchSchool = { borough: area_id, block: area_id };
    const schools = await searchSchool(params, 1, 1000);
    if (schools.success) {
      return schools?.data?.items?.map(item => ({
        label: item.school_name,
        value: item.id,
      }));
    }
  }
  return [];
};
export const getGradesOptionsBySchool = async (school_id: string): Promise<any> => {
  if (school_id) {
    const r = await listGrades(school_id);
    if (r.success) {
      return r?.data?.items?.map(item => {
        return {
          label: item.grade_name,
          value: String(item.id),
          key: item.id,
        };
      });
    }
  }
  return [];
};
export const getGradesOptions = async (form: FormPanelObject): Promise<any> => {
  if (form && form.getFieldsValue()?.school_id) {
    const r = await listGrades(form.getFieldsValue()?.school_id);
    if (r.success) {
      return r?.data?.items?.map(item => {
        return {
          label: item.grade_name,
          value: String(item.id),
          key: item.id,
        };
      });
    }
  }
  return [];
};
export const getClassesOptionsBySchool = async (school_id: string, form: FormPanelObject): Promise<any> => {
  if (form && form.getFieldsValue()?.grade_id) {
    const r = await listClasses(school_id, form.getFieldsValue()?.grade_id);
    if (r.success) {
      return r.data?.items?.map(item => ({
        label: `${item.class_name}班`,
        value: String(item.id),
        key: item.id,
      }));
    }
  }
  return [];
};
export const getClassesOptions = async (form: FormPanelObject): Promise<any> => {
  if (form && form.getFieldsValue()?.grade_id) {
    const r = await listClasses(form.getFieldsValue()?.school_id, form.getFieldsValue()?.grade_id);
    if (r.success) {
      return r.data?.items?.map(item => ({
        label: `${item.class_name}班`,
        value: String(item.id),
        key: item.id,
      }));
    }
  }
  return [];
};

// export const getClassesOptionsBySchool = async (form: FormPanelObject) => {
//   if (form && form.getFieldsValue()?.school_id) {
//     const r = await listClasses(form.getFieldsValue()?.school_id);
//     if (r.success) {
//       return r.data?.items?.map(item => ({
//         label: `${item.class_name}班`,
//         value: String(item.id),
//         key: item.id,
//       }));
//     }
//   }
//   return [];
// };

export const getMajorOptionsBySchool = async (form: FormPanelObject): Promise<any> => {
  if (form && form.getFieldsValue()?.school_id) {
    const data = await searchMajor(form.getFieldsValue()?.school_id);
    if (data.success) {
      return data?.data?.items?.map(item => {
        return {
          label: item.major_name,
          value: String(item.major_no),
          key: item.major_no,
        };
      });
    }
  }
  return [];
};

export const getGradeClassOptions = async (form: FormPanelObject): Promise<any> => {
  let list = [];
  if (form && form.getFieldsValue()?.school_id) {
    const grades = await listGrades(form.getFieldsValue()?.school_id);
    const classes = await listClasses(form.getFieldsValue()?.school_id);
    if (grades?.data?.items && classes?.data?.items) {
      list = grades?.data?.items?.map(item => {
        return {
          label: item.grade_name,
          value: String(item.id),
          key: item.id,
          children: classes?.data?.items
            ?.filter(v => v.grade_id === item.id)
            .map(v => {
              return {
                label: `${v.class_name}班`,
                value: String(v.id),
                key: v.id,
              };
            }),
        };
      });
    }
  }
  return list;
};

export const searchSchoolOptions = async (
  formPanelObject: FormPanelObject,
  searchTxt: string,
  schoolId?: any
): Promise<any> => {
  if (schoolId) {
    const res = await getSchool(schoolId);
    if (res.success) {
      return [
        {
          label: res.data?.school?.school_name,
          value: res.data?.school?.id,
        },
      ];
    }
  }
  const res = await searchSchoolByName(searchTxt, 1, 100);
  if (res.success) {
    return res.data.map(item => ({
      label: item.school_name,
      value: item.id,
    }));
  }
  return [];
};

export const searchSchoolByKeyOptions = async (
  formPanelObject: FormPanelObject,
  searchTxt: string,
  params: Omit<SearchSchoolByNameParams, 'school_name'>
): Promise<any> => {
  // if (searchTxt) {
  //   const res = await searchByNameSchool({ ...params, school_name: searchTxt, page: 1, per_page: 50 });
  //   if (res.success) {
  //     return res.data.map(item => ({
  //       label: item.school_name,
  //       value: item.id,
  //     }));
  //   }
  // } else if (params && params.school_id) {
  //   const res = await getSchool(formPanelObject.searchByNameSchool({ ...params, page: 1, per_page: 50 }));
  //   if (res.success) {
  //     return [
  //       {
  //         label: res.data?.school?.school_name,
  //         value: res.data?.school?.id,
  //       },
  //     ];
  //   }
  // }
  const res = await searchByNameSchool({ ...params, school_name: searchTxt, page: 1, per_page: 50 });
  if (res.success) {
    return res.data.map(item => ({
      label: item.school_name,
      value: item.id,
    }));
  }
  return [];
};

export const searchPlanningSchoolOptions = async (
  formPanelObject: FormPanelObject,
  searchTxt: string
): Promise<any> => {
  if (formPanelObject.getFieldValue('planning_school_id')) {
    const res = await getPlanningSchoolById(formPanelObject.getFieldValue('planning_school_id'));
    if (res.success) {
      return [
        {
          label: res.data?.planning_school?.planning_school_name,
          value: res.data?.planning_school?.id,
        },
      ];
    }
  }
  const res = await searchPlanningSchoolByName(searchTxt);
  if (res.success) {
    return res.data.map(item => ({
      label: item.planning_school_name,
      value: item.id,
    }));
  }
  return [];
};

export const searchOrgs = async (): Promise<any> => {
  const res = await searchOrg({});
  if (res.success) {
    return res.data.items
      .filter(it => String(it.parent_id) === '0')
      .map(item => {
        return {
          label: item.org_name,
          value: String(item.id),
          children: res.data.items
            .filter(it => it.parent_id === item.id)
            .map(subitem => {
              return {
                label: subitem.org_name,
                value: String(subitem.id),
                children: res.data.items
                  .filter(it => it.parent_id === subitem.id)
                  .map(subitem => {
                    return {
                      label: subitem.org_name,
                      value: String(subitem.id),
                    };
                  }),
              };
            }),
        };
      });
  }
  return [];
};

export const getPlanningSchoolCategoryOptions = (form: FormPanelObject, key: string): Array<any> => {
  const edu_level = form.getFieldValue(key);
  if (edu_level) {
    const school_category: any = SCHOOL_OPERATION_TYPE.find(it => {
      return it.value === edu_level;
    });
    if (Utils.getProps('edu_type') === 'secondaryVocationalSchool') {
      return school_category?.children.filter(it => {
        return it.value === 'secondaryVocationalSchool';
      });
    }
    return school_category?.children;
  }
  return [];
};

export const getPlanningSchoolOperationTypeOptions = (
  form: FormPanelObject,
  key1: string,
  key2: string
): Array<any> => {
  const edu_level = form.getFieldValue(key1);
  const category_options: any = form.getFieldValue(key2);
  //console.log(edu_level, category_options, '============>>>>');
  if (edu_level && category_options) {
    const school_category: any = SCHOOL_OPERATION_TYPE.find(it => {
      return it.value === edu_level;
    });
    return school_category?.children?.find(it => {
      return it.value === category_options;
    })?.children;
  }
  return [];
};

export const getGradeTypeOptions = async (): Promise<any> => {
  const gradeTypes = await listGradeType();
  if (gradeTypes.success) {
    return gradeTypes?.data?.items?.map(item => {
      return {
        label: item.description,
        value: item.enum_value,
      };
    });
  }
  return [];
};

export const searchTeacherOptions = async (form: FormPanelObject, searchTxt: string): Promise<any> => {
  const res = await TeachersSrv.list({ teacher_name: searchTxt, page: 1, per_page: 50 });
  if (res.success) {
    return res?.data?.items?.map(item => {
      return {
        label: item.teacher_name,
        value: item.teacher_id,
      };
    });
  }
  return [];
};

export const searchStudentOptions = async (form: FormPanelObject, searchTxt: string): Promise<any> => {
  const res = await getStuInfo({ student_name: searchTxt, page: 1, per_page: 50 });
  if (res.success) {
    return res?.data?.items?.map(item => {
      return {
        label: item.student_name,
        value: item.student_id,
      };
    });
  }
  return [];
};

// 获取当前学校年级
export const getGradeOptions = async (): Promise<any> => {
  const res = await listGrades(Utils.getProps('schoolInfo')?.school_id);
  if (res.success) {
    const arr = res?.data?.items?.map(item => {
      return {
        label: item.grade_name,
        value: `${item.id}`,
      };
    });
    return arr;
  }
  return [];
};

export const getCourseOptions = async (): Promise<any> => {
  const res = await selectedCourse(Utils.getProps('schoolInfo')?.school_id, 1, 1000);
  if (res.success) {
    return res?.data?.items?.map(item => {
      return {
        label: item.course_name,
        value: item.course_no,
      };
    });
  }
  return [];
};

export const getEduLevelOptions = async (): Promise<any> => {
  if (Utils.getProps('edu_type') === 'kg') {
    return SCHOOL_OPERATION_TYPE.filter(item => item.value === 'preSchoolEducation');
  }
  if (Utils.getProps('edu_type') === 'k12') {
    return SCHOOL_OPERATION_TYPE.filter(item =>
      [
        'primaryEducation',
        'secondaryEducation',
        'ordinaryHighSchool',
        'specialEducation',
        'otherEducation',
        'trainingInstitution',
      ].includes(item.value)
    );
  }
  if (Utils.getProps('edu_type') === 'vocational') {
    return SCHOOL_OPERATION_TYPE.filter(item => item.value === 'secondaryEducation');
  }
  return SCHOOL_OPERATION_TYPE;
};
